import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import { Alert, Button, Card, message } from 'antd';
import { EllipsisTooltip } from '@/molecules';
import styles from './style.less';
import { getRecruitmentUpdated, queryRecruitmentUpdate } from '../../service';

const DemandFieldUpdate = memo(({ style, onRefresh = () => {}, outwardId = '' }) => {
    const [title, setTitle] = useState('');
    const [isUpdate, setIsUpdate] = useState(false);
    const refAlter = useRef();
    const handleQuery = useCallback(async (e, updated) => {
        try {
            const { code, msg } = await queryRecruitmentUpdate({
                outwardId,
                dealType: updated ? 2 : 1
            });
            if (code === 10000) {
                if (updated) onRefresh();
                refAlter.current.handleClose(e);
            } else {
                message.error(msg);
            }
        } catch (err) {
            console.log(err);
        }
    }, [outwardId]);
    const queryUpdateStatus = async () => {
        try {
            const { data = {}, code, msg } = await getRecruitmentUpdated(outwardId);
            if (code === 10000) {
                if (data.hasChange) {
                    setIsUpdate(true);
                    setTitle(`本次变更字段：${data.changeColumn}`);
                }
            } else {
                message.error(msg)
            }
        } catch (e) {
            console.log(e);
        }
    }
    useEffect(() => {
        if (outwardId) {
            queryUpdateStatus();
        }
    }, [outwardId])
    return isUpdate ?
        <Card
            bordered={false}
            style={style}
        >
            <Alert
                ref={refAlter}
                message="招聘原始需求已变更，发布时是否更新变更字段"
                description={
                    <div>
                        <EllipsisTooltip
                            style={{ marginBottom: 0 }}
                        >
                            {title}
                        </EllipsisTooltip>
                        <div className={styles.buttonWrap}>
                            <Button type="link" onClick={e => handleQuery(e)}>本次不更新</Button>
                            <Button type="link" onClick={e => handleQuery(e, true)}>立即更新</Button>
                        </div>
                    </div>
                }
                onClose={() => setIsUpdate(false)}
                type="warning"
                showIcon
                closable
            />
        </Card> : null
})
export default DemandFieldUpdate;
